package com.xsq.view;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xsq.R;

import org.xutils.common.util.LogUtil;

public class DelayDialog extends ProgressDialog {

    private TextView textView;
    private EditText editText;
    private Button cancel;

    private TextWatcher textWatcher;

    public DelayDialog(Context context) {
        super(context);
    }

    public DelayDialog(Context context, int theme) {
        super(context, theme);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(getContext());
    }

    public void setMessageText(String loadingText) {
        this.textView.setText(loadingText);
    }

    public EditText getEditText() {
        return this.editText;
    }

    public Button getCancelBtn() {
        return this.cancel;
    }

    public void notify(final EditText editCard) {
        //1、移除原来的文字改变监听，避免列表刷新或者view复用所造成TextWatcher被多次调用
        if (textWatcher !=null){
            this.editText.removeTextChangedListener(textWatcher);
        }
        //2 创建TextWatcher
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                String sn = s.toString();
                LogUtil.e("---弹窗接收到条码扫描---" + sn);
                if (!TextUtils.isEmpty(sn) && sn.length() == 8) {
                    editCard.setText(sn);
                }
            }
        };
        //3 先移除，后添加
        this.editText.addTextChangedListener(textWatcher);
        this.editText.setVisibility(View.VISIBLE);
        this.editText.requestFocus();
    }

    private void init(Context context) {
        setCancelable(true);
        setCanceledOnTouchOutside(false);

        setContentView(R.layout.view_delay_dialog);//loading的xml文件
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(params);
        textView = findViewById(R.id.tv_message);
        editText = findViewById(R.id.edit_text);
        cancel = findViewById(R.id.cancel);
    }

    @Override
    public void show() {//开启
        super.show();
    }

    @Override
    public void dismiss() {//关闭
        super.dismiss();
    }

}
